import Base from "../base.js";
import StudentsApi from "../../api/students.js";
import config from "../../util/config.js";
import Student from "./students.js";

export default class extends Base {
    constructor(props) {
        super(props)
        this.data = {
            student: { _id: props._id }
        }
    }
    handle() {
        this.$back.on("click", e => {
            location.hash = "#/info/student";
        });
        this.$imgs.on("click", "img", async e => {
            const url = e.target.src.replace(config["api-server"], "");
            await StudentsApi.deleteImg({ url, _id: this.data.student._id });
            this.getOne();
        });
        layui.upload.render({
            elem: '#test1'
            , url: '/resource/students/upload' //改成您自己的上传接口
            , multiple: true
            , data: {
                _id: this.data.student._id
            }
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            }
            , done: res => {
                this.getOne();
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });
    }
    async mounted() {
        this.getOne();
    }
    async getOne() {
        const data = await StudentsApi.getOne(this.data.student._id);
        Object.assign(this.data.student, data);
        this.rerender();
    }
    rerender() {
        this.$span.text(this.data.student.name);
        this.$imgs.html(`
                ${this.data.student.imgs.map(item => `<img src="${config["api-server"]}${item}" style="width:300px;height:200px"/>`).join("")
            }
            `);
    }
    render() {
        this.$el.html(`
            <div><h1>添加图片</h1></div>
            <div><p>姓名：<span class="name"></span></p></div>
            <p>学生图片</p>
            <button type="button" class="layui-btn" id="test1">上传图片</button>
            <button class="back-btn">返回</button>
            <div class="imgs"></div>
        `);
        this.$span = $(".name");
        this.$imgs = $(".imgs");
        this.$back = $(".back-btn");
    }
}